package com.sojson.config.init;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import com.sojson.project.sentinel.dao.SentinelDao;
import com.sojson.project.sentinel.entity.dto.SentinelDto;
import com.sojson.project.sentinel.entity.vo.SentinelVo;
import com.sojson.util.cache.CacheUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义初始化类(必须通过@Bean注解注入,否则会提前执行,导致出现一些空指针异常)</BR>
 * 执行顺序由@org.springframework.context.annotation.DependsOn指定</BR>
 *
 * @author liu
 * @date 2021-09-13
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebInit implements InitializingBean {

    @Resource
    private SentinelDao sentinelDao;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化系统属性
        initSystemParam();
    }

    /**
     * 初始化系统属性
     *
     * @throws IOException
     */
    public void initSystemParam() throws IOException {
        // 开始设置字典
        log.info("开始设置Sentinel流控！");

        // 查询所有属性
        List<SentinelVo> list = sentinelDao.list(new SentinelDto());
        for (SentinelVo sentinel : list) {
            CacheUtil.CACHE_REDIS.setStr(sentinel.getKey(), sentinel.getContent());
        }

        log.info("Sentinel流控已加载到缓存！");
    }

}